package com.atguigu.srb.sms.service.impl;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.atguigu.srb.common.utils.RandomUtils;
import com.atguigu.srb.sms.config.SmsProperties;
import com.atguigu.srb.sms.service.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class SmsServiceImpl implements SmsService {

    @Autowired
    RedisTemplate redisTemplate;



    @Override
    public void sendRegisterCode(String mobile) {
        // 设置公共参数
        DefaultProfile defaultProfile = DefaultProfile.
                getProfile(SmsProperties.REGION_Id,SmsProperties.KEY_ID,SmsProperties.KEY_SECRET);

        // 阿里云客户端工具
        IAcsClient iAcsClient = new DefaultAcsClient(defaultProfile);

        // 配置请求参数
        CommonRequest commonRequest = new CommonRequest();
        commonRequest.setSysAction("SendSms");
        commonRequest.setSysMethod(MethodType.POST);
        commonRequest.setSysVersion("2017-05-25");
        commonRequest.setSysDomain("dysmsapi.aliyuncs.com");// 阿里网关
        commonRequest.putQueryParameter("PhoneNumbers",mobile);
        commonRequest.putQueryParameter("SignName",SmsProperties.SIGN_NAME);
        commonRequest.putQueryParameter("TemplateCode",SmsProperties.TEMPLATE_CODE);
        Map<String,Object> map = new HashMap<>();
        String sixBitRandom = RandomUtils.getSixBitRandom();
        map.put("code",sixBitRandom);
        String TemplateParam = JSON.toJSONString(map);
        commonRequest.putQueryParameter("TemplateParam",TemplateParam);
        // 发送短信
        CommonResponse commonResponse = null;
        try {
            commonResponse = iAcsClient.getCommonResponse(commonRequest);
        } catch (ClientException e) {
            throw new RuntimeException(e);
        }
        // 解析返回结果
        boolean success = commonResponse.getHttpResponse().isSuccess();
        if (success) {
            redisTemplate.opsForValue().set("srb:sms:code:"+mobile,sixBitRandom);
        }
    }
}
